from sentence_transformers import SentenceTransformer, util
#https://modelscope.cn/models/Jerry0/text2vec-base-chinese
#https://modelscope.cn/models/mwei23/text2vec-base-chinese-paraphrase
m = SentenceTransformer("mwei23/text2vec-base-chinese-paraphrase")
sentences = ['如何更换花呗绑定银行卡', '花呗更改绑定银行卡','早上好']
query = '你好'
# 编码句子和查询
sentence_embeddings = m.encode(sentences, convert_to_tensor=True)
def rank_docs(query,docs,docs_embedding,topk):
    query_embedding = m.encode([query], convert_to_tensor=True)
    cosine_scores = util.pytorch_cos_sim(query_embedding, docs_embedding)[0]
    sorted_sentences = [docs[i] for i in cosine_scores.argsort(descending=True)]
    # 输出排序后的句子
    return sorted_sentences[:topk]
def run():
    query_embedding = m.encode([query], convert_to_tensor=True)
    # 计算查询向量和每个句子向量之间的余弦相似度
    cosine_scores = util.pytorch_cos_sim(query_embedding, sentence_embeddings)[0]
    # 根据相似度分数对句子进行排序
    sorted_sentences = [sentences[i] for i in cosine_scores.argsort(descending=True)]
    # 输出排序后的句子
    print("排序后的句子（从最相似到最不相似）:")
    for sentence in sorted_sentences:
        print(sentence)
